package echo.netty;

import io.netty.channel.ChannelHandler;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelOutboundHandlerAdapter;
import io.netty.channel.ChannelPromise;

import java.util.logging.Level;
import java.util.logging.Logger;

/**
 * @author： zhangnan
 * @date： 2025/4/9 18:53
 * @description： TODO
 * @modifiedBy：出站日志处理器
 * @version: 1.0
 */
// 标记为线程安全，可被多个Channel共享
@ChannelHandler.Sharable
public class LoggingOutboundHandler extends ChannelOutboundHandlerAdapter {
    private static final Logger logger = Logger.getLogger(LoggingOutboundHandler.class.getName());
    private final String name;

    public LoggingOutboundHandler(String name) {
        this.name = name;
    }

    // 处理出站数据写入事件
    @Override
    public void write(ChannelHandlerContext ctx, Object msg, ChannelPromise promise){
        logger.log(Level.INFO, "{0} - 开始处理出站消息: {1}", new Object[]{name, msg});
        // 继续执行出站数据写入操作
//        super.write().write(msg,promise);
        logger.log(Level.INFO, "{0} - 出站消息处理完成", name);
    }

    public void exceptionCaught(ChannelHandlerContext ctx,Throwable cause){
        logger.log(Level.SEVERE, "{0} - 出站发生异常: ", new Object[]{name, cause});
        ctx.close();
    }




}